<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class RoleController extends Controller
{
	//权限管理首页
    public function getIndex(Request $request)
    {
        // dd($request->all());
        if($request['name']){
            //搜索分页
            $res = DB::table('role')
            ->where('RoleName','like','%'.$request['name'].'%')
            ->paginate(2);
        }else{
            //所有分页
            $res = DB::table('role')
            ->paginate(2);
        }
        // dd($res);
        $info = $request -> all();

        //解析页面
        return view('department/role/role',['res'=>$res,'info'=>$info]);

    } 
    
    //添加
    public function getAdd()
    {

    	$res = DB::table('group')->get();
        

        return view('department/role/add',['res'=>$res]);

    }

    //执行添加
    public function postInsert(Request $request)
    {
        //表单验证
        $this->validate($request, [
        'RoleName' => 'required|unique:role,RoleName',
        'GroupId' => 'required',
        'Remark' => 'required',
        ],[
        'RoleName.required'=>'角色名称不能为空',
        'RoleName.unique'=>'角色名称已存在',
        'GroupId.required'=>'分组ID不能为空',
        'Remark.required'=>'备注不能为空',
        ]);
        $res = $request->only('RoleName','GroupId','Remark');
        $res['GroupId'] = implode(',',$res['GroupId']);
        // dd($res);
        //执行添加
        DB::table('role')->insert($res);

        return redirect('/department/role')->with('success','添加成功');
    }

    //修改
    public function getEdit($id)
    {
        $res = DB::table('role')->where('id',$id)->get();
        $res[0]['GroupId'] = explode(',',DB::table('role')->where('id',$id)->value('GroupId'));
        $group = DB::table('group')->get();
        // dd($res);
        return view('/department/role/edit',['res'=>$res,'group'=>$group]);
    }

    //执行修改
    public function postUpdate(Request $request)
    {
        $res = $request->only('id','RoleName','GroupId','Remark');
        $res['GroupId'] = implode(',',$res['GroupId']);
        // dd($res);
        DB::table('role')->where('id',$res['id'])->update($res);
        return redirect('/department/role');

    }

    //删除
    public function getDel($id)
    {
        DB::table('role')->where('id',6)->delete();
        return redirect('/department/role');
        
    }
}
